import axios from 'axios'
import { E } from '../configs'

function filterJSON(res) {
    return res.data;
}

//通过对response的解析, 确定解析成功或者失败
function filterStatus(res) {
    if (res.status >= 200 && res.status < 300) {
        return res;
    } else {

    }
}

function rp(path, params, method, header = null) {
    if (-1 == path.indexOf('http:') && -1 == path.indexOf('https:')) {
        path = E.SERVER_HOME + path
    }

    // 传入参数
    let options = {
        headers: {
            'Cache-Control': 'no-cache',
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        },
        timeout: 60000,
        method
    }
    console.log('params', params);
    // 传入参数
    // return null
    switch (method) {
        case 'GET':
        case 'DELETE':
            options.params = params || {};
            break
        case 'POST':
        case 'PUT':
        case 'PATCH':
            options.data = params;
            break
    }
    console.log('[REQ]', path, options);

    // 发起请求
    return axios(path, options)
        .then(filterStatus)
        .then(filterJSON)
        .then(response => {
            console.log('response', response);
            
            if (response.error) {
                console.log('[ERR]', response);
                return { error: response }
            } else {
                console.log('[ACK]', path, response);
                return { response }
            }
        })
        .catch(error => {
            return { error }
        })
}

class AxiosUtil {

    static get(path, params, header = null) {
        return rp(path, params, 'GET', header)
    }

    static post(path, params, header = null) {
        return rp(path, params, 'POST', header = null)
    }
}

export default AxiosUtil